# -*- coding: UTF-8 -*-

#Natural Language Toolkit: Eliza
#
# Copyright (C) 2001-2010 NLTK Project
# Authors: Steven Bird <sb@csse.unimelb.edu.au>
#          Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT

# Based on an Eliza implementation by Joe Strout <joe@strout.net>,
# Jeff Epler <jepler@inetnebr.com> and Jez Higgins <mailto:jez@jezuk.co.uk>.

# A modified version for polish language with personalisation
# @author: Marcin Harasimczuk

from nltk.chat.util import *
import codecs
import xml.parsers.expat
from lxml import etree
import analizer

# Global variables for XML parsing of already filled response file
pairs = []              # List of pair elements
pair = []               # (rexp, tuple(resps)) 
rexp = ''               # Regular expression
resps = []              # List of responses
xmlElement = ''         # Current XML element

# XML Parsing handlers
def start_element(name, attrs):
        global xmlElement
        
        # Remember current element
        xmlElement = name

def end_element(name):
        global rexp
        global resps
        global pair
        global pairs

        # If pair ends add it to pairs
        if name == "pair" :
                pair = ( rexp, tuple(resps) )
                pairs.append(pair)
                resps = []


def char_data(data):
        global xmlElement
        global rexp
        global resps

        if xmlElement == "rexp" :
                rexp = data.encode('UTF-8')
        if xmlElement == "resp" :
                resps.append(data.encode('UTF-8'))
        if xmlElement == "luka" :
                currentResp = resps.pop()
                newResp = currentResp + data.encode('UTF-8')
                resps.append(newResp)
        if xmlElement == "nick" :
                currentResp = resps.pop()
                newResp = currentResp + data.encode('UTF-8')
                resps.append(newResp)


# Stalker chat-bot
def stalker_chat():
        global pairs
        
        # Initialize history analizer
        analizer.parseHistory("log/gadu-gadu/7056873")
        analizer.parseAliases("blist.xml")

        # Fill in riddled XML with data retrieved from History
        token = []
        # Read riddled XML file
        responsesXMLTree = etree.parse('response.xml')
        # Find all responses
        responsesXML = responsesXMLTree.findall("/pair/resp")
        for responseXML in responsesXML:
                nickElement = responseXML.find("nick")
                # Find all gaps
                gapsXML = responseXML.findall("luka")
                firstGap = True
                for gapXML in gapsXML:
                        if firstGap == True:
                                token = analizer.fillTheGap(gapXML.text)
                                if token:
                                        gapXML.text = token[0]
                                        if nickElement is not None:
                                                nickElement.text = analizer.getAlias(token[2])

                                firstGap = False
                        else:
                                # First gap filling was a success
                                if token:
                                        nextToken = analizer.fillTheGap(gapXML.text, firstGap=False, previous=(token[2],token[1]))
                                        if nextToken:
                                                gapXML.text = nextToken[0]
                                # Analizer was unable to fill the first gap
                                else: 
                                        token = analizer.fillTheGap(gapXML.text)
                                        if token:
                                                gapXML.text = token[0]

                                # If first gap was not filled try to get nick from the second gap filling
                                if nickElement is not None and nickElement == "Nick" and token:
                                                nickElement.text = analizer.getAlias(token[2])

        outFile = open('out.xml', 'w')
        outFile.write(etree.tostring(responsesXMLTree, xml_declaration=True, encoding='UTF-8'))
        # Need to close file to save changes
        outFile.close()

        # Parse ready XML file and feed the results to chat-bot
        f = open('out.xml', 'r')
        
        p = xml.parsers.expat.ParserCreate()
        p.StartElementHandler = start_element
        p.EndElementHandler = end_element
        p.CharacterDataHandler = char_data
        p.ParseFile(f)

        # Start chat-bot
        stalker_chatbot = Chat(pairs, reflections)

        # Introduction text
        print "Stalker\n"
        print "Rozmawiasz na czacie. Odpowiadaj nieformalnie, w języku polskim."
        print '='*72
        print "Hej! Co tam?"

        # Start chat-bot
        stalker_chatbot.converse()

# Main function
def stalk():
        stalker_chat()

if __name__ == "__main__":
        stalk()
  
